<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理系统</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" 
          integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
        }
        .container {
            margin-top: 20px;
        }
        .header {
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #dee2e6;
        }
        .card {
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
        }
        .btn-primary:hover {
            background-color: #0056b3;
            border-color: #0056b3;
        }
        .btn-danger {
            background-color: #dc3545;
            border-color: #dc3545;
        }
        .btn-danger:hover {
            background-color: #c82333;
            border-color: #bd2130;
        }
        .btn-success {
            background-color: #28a745;
            border-color: #28a745;
        }
        .btn-success:hover {
            background-color: #218838;
            border-color: #1e7e34;
        }
        .btn-warning {
            background-color: #ffc107;
            border-color: #ffc107;
            color: #212529;
        }
        .btn-warning:hover {
            background-color: #e0a800;
            border-color: #d39e00;
            color: #212529;
        }
        .status-badge {
            padding: 5px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        .status-active {
            background-color: #d4edda;
            color: #155724;
        }
        .status-inactive {
            background-color: #f8d7da;
            color: #721c24;
        }
        .action-buttons {
            white-space: nowrap;
        }
        .table-responsive {
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .search-box {
            margin-bottom: 20px;
        }
        .form-control:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
        }
        .modal-header {
            background-color: #007bff;
            color: white;
        }
        .alert {
            margin-top: 15px;
        }
        .no-data {
            text-align: center;
            padding: 50px;
            color: #6c757d;
            font-style: italic;
        }
        .spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(0, 123, 255, 0.3);
            border-radius: 50%;
            border-top-color: #007bff;
            animation: spin 1s ease-in-out infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* 返回首页按钮样式 */
        .home-button {
            background-color: rgba(0, 123, 255, 0.1);
            border: 1px solid #007bff;
            color: #007bff;
            padding: 8px 16px;
            border-radius: 6px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        
        .home-button:hover {
            background-color: #007bff;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 123, 255, 0.2);
            text-decoration: none;
        }
        
        .home-button i {
            margin-right: 6px;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .header {
                text-align: center;
            }
            
            .header-buttons {
                margin-top: 15px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1><i class="fa fa-users" aria-hidden="true"></i> 用户管理系统</h1>
                    <p>管理系统所有用户的信息和状态</p>
                </div>
                <div class="header-buttons">
                    <a href="/home" class="home-button">
                        <i class="fa fa-home" aria-hidden="true"></i> 返回首页
                    </a>
                </div>
            </div>
        </div>

        <!-- 消息提示区域 -->
        <div id="message" class="alert alert-success" style="display: none;">
            <span id="message-text"></span>
        </div>

        <!-- 操作按钮区域 -->
        <div class="card p-4 mb-4">
            <div class="row">
                <div class="col-md-6">
                    <button id="add-user-btn" class="btn btn-primary btn-lg">
                        <i class="fa fa-plus-circle" aria-hidden="true"></i> 添加新用户
                    </button>
                </div>
                <div class="col-md-6 search-box">
                    <div class="input-group">
                        <input type="text" id="search-input" class="form-control" placeholder="搜索用户名、邮箱或真实姓名...">
                        <button id="search-btn" class="btn btn-secondary">
                            <i class="fa fa-search" aria-hidden="true"></i> 搜索
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 用户列表表格 -->
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h3 class="mb-0">用户列表</h3>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover table-striped">
                        <thead class="bg-light">
                            <tr>
                                <th>ID</th>
                                <th>用户名</th>
                                <th>真实姓名</th>
                                <th>邮箱</th>
                                <th>手机号</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="user-table-body">
                            <!-- 用户数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
                <div id="loading-indicator" class="text-center py-5" style="display: none;">
                    <div class="spinner mx-auto"></div>
                    <p class="mt-2">正在加载用户数据...</p>
                </div>
                <div id="no-data-message" class="no-data" style="display: none;">
                    <i class="fa fa-info-circle" aria-hidden="true"></i> 暂无用户数据
                </div>
            </div>
        </div>
    </div>

    <!-- 添加用户模态框 -->
    <div class="modal fade" id="add-user-modal" tabindex="-1" role="dialog" aria-labelledby="add-user-modal-label" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="add-user-modal-label">添加新用户</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="add-user-form">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="add-username">用户名 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="add-username" name="username" required>
                                </div>
                                <div class="form-group">
                                    <label for="add-password">密码 <span class="text-danger">*</span></label>
                                    <input type="password" class="form-control" id="add-password" name="password" required>
                                </div>
                                <div class="form-group">
                                    <label for="add-real-name">真实姓名 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="add-real-name" name="realName" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="add-email">邮箱 <span class="text-danger">*</span></label>
                                    <input type="email" class="form-control" id="add-email" name="email" required>
                                </div>
                                <div class="form-group">
                                    <label for="add-phone">手机号</label>
                                    <input type="tel" class="form-control" id="add-phone" name="phone">
                                </div>
                                <div class="form-group">
                                    <label for="add-status">状态</label>
                                    <select class="form-control" id="add-status" name="status">
                                        <option value="1">启用</option>
                                        <option value="0">禁用</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" id="save-user-btn" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div class="modal fade" id="edit-user-modal" tabindex="-1" role="dialog" aria-labelledby="edit-user-modal-label" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="edit-user-modal-label">编辑用户</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="edit-user-form">
                        <input type="hidden" id="edit-user-id" name="id">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit-username">用户名 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="edit-username" name="username" required readonly>
                                </div>
                                <div class="form-group">
                                    <label for="edit-password">密码 (留空不修改)</label>
                                    <input type="password" class="form-control" id="edit-password" name="password" placeholder="留空则不修改密码">
                                </div>
                                <div class="form-group">
                                    <label for="edit-real-name">真实姓名 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="edit-real-name" name="realName" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit-email">邮箱 <span class="text-danger">*</span></label>
                                    <input type="email" class="form-control" id="edit-email" name="email" required>
                                </div>
                                <div class="form-group">
                                    <label for="edit-phone">手机号</label>
                                    <input type="tel" class="form-control" id="edit-phone" name="phone">
                                </div>
                                <div class="form-group">
                                    <label for="edit-status">状态</label>
                                    <select class="form-control" id="edit-status" name="status">
                                        <option value="1">启用</option>
                                        <option value="0">禁用</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" id="update-user-btn" class="btn btn-primary">更新</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="delete-confirm-modal" tabindex="-1" role="dialog" aria-labelledby="delete-confirm-modal-label" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title" id="delete-confirm-modal-label">确认删除</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>您确定要删除用户 <strong id="delete-username"></strong> 吗？此操作无法撤销。</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" id="confirm-delete-btn" class="btn btn-danger">确认删除</button>
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" 
            integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
    <!-- Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <script>
        // 当前要操作的用户ID
        let currentUserId = null;
        let currentUsername = null;
        let users = [];

        // 页面加载完成后执行
        $(document).ready(function() {
            // 加载用户列表
            loadUsers();

            // 添加用户按钮点击事件
            $('#add-user-btn').click(function() {
                $('#add-user-form')[0].reset();
                $('#add-user-modal').modal('show');
            });

            // 保存用户按钮点击事件
            $('#save-user-btn').click(function() {
                saveUser();
            });

            // 搜索按钮点击事件
            $('#search-btn').click(function() {
                searchUsers();
            });

            // 搜索输入框回车事件
            $('#search-input').keypress(function(e) {
                if (e.which === 13) {
                    searchUsers();
                }
            });

            // 更新用户按钮点击事件
            $('#update-user-btn').click(function() {
                updateUser();
            });

            // 确认删除按钮点击事件
            $('#confirm-delete-btn').click(function() {
                deleteUser();
            });
        });

        // 加载用户列表
        function loadUsers() {
            showLoading(true);
            clearMessages();

            axios.get('/api/user-management/users')
                .then(function(response) {
                    users = response.data;
                    renderUserTable(users);
                })
                .catch(function(error) {
                    console.error('加载用户列表失败:', error);
                    showMessage('加载用户列表失败，请刷新页面重试', 'danger');
                    $('#no-data-message').show();
                })
                .finally(function() {
                    showLoading(false);
                });
        }

        // 渲染用户表格
        function renderUserTable(userList) {
            const tableBody = $('#user-table-body');
            tableBody.empty();

            if (userList.length === 0) {
                $('#no-data-message').show();
                return;
            }

            $('#no-data-message').hide();

            userList.forEach(function(user) {
                const statusClass = user.status === 1 ? 'status-active' : 'status-inactive';
                const statusText = user.status === 1 ? '启用' : '禁用';
                const toggleStatusText = user.status === 1 ? '禁用' : '启用';
                const toggleStatusBtnClass = user.status === 1 ? 'btn-warning' : 'btn-success';
                const toggleStatusIcon = user.status === 1 ? 'fa-lock' : 'fa-unlock';

                // 格式化日期时间
                const createTime = formatDateTime(user.createTime);

                const row = $('<tr>').append(
                    $('<td>').text(user.id),
                    $('<td>').text(user.username),
                    $('<td>').text(user.realName || '-'),
                    $('<td>').text(user.email || '-'),
                    $('<td>').text(user.phone || '-'),
                    $('<td>').html(`<span class="status-badge ${statusClass}">${statusText}</span>`),
                    $('<td>').text(createTime),
                    $('<td>').addClass('action-buttons').append(
                        $('<button>')
                            .addClass('btn btn-primary btn-sm mr-2')
                            .html('<i class="fa fa-pencil" aria-hidden="true"></i> 编辑')
                            .click(function() {
                                editUser(user.id);
                            }),
                        $('<button>')
                            .addClass(`btn ${toggleStatusBtnClass} btn-sm mr-2`)
                            .html(`<i class="fa ${toggleStatusIcon}" aria-hidden="true"></i> ${toggleStatusText}`)
                            .click(function() {
                                toggleUserStatus(user.id, user.status === 1 ? 0 : 1, user.username);
                            }),
                        $('<button>')
                            .addClass('btn btn-danger btn-sm')
                            .html('<i class="fa fa-trash" aria-hidden="true"></i> 删除')
                            .click(function() {
                                prepareDeleteUser(user.id, user.username);
                            })
                    )
                );

                tableBody.append(row);
            });
        }

        // 保存新用户
        function saveUser() {
            const formData = {
                username: $('#add-username').val(),
                password: $('#add-password').val(),
                realName: $('#add-real-name').val(),
                email: $('#add-email').val(),
                phone: $('#add-phone').val(),
                status: parseInt($('#add-status').val())
            };

            // 表单验证
            if (!formData.username || !formData.password || !formData.realName || !formData.email) {
                showMessage('请填写所有必填字段', 'danger');
                return;
            }

            axios.post('/api/user-management/users', formData)
                .then(function(response) {
                    if (response.data.success) {
                        $('#add-user-modal').modal('hide');
                        showMessage(response.data.message, 'success');
                        loadUsers(); // 重新加载用户列表
                    } else {
                        showMessage(response.data.message, 'danger');
                    }
                })
                .catch(function(error) {
                    console.error('保存用户失败:', error);
                    showMessage('保存用户失败，请稍后重试', 'danger');
                });
        }

        // 编辑用户
        function editUser(id) {
            showLoading(true);
            clearMessages();

            axios.get(`/api/user-management/users/${id}`)
                .then(function(response) {
                    const user = response.data;
                    currentUserId = user.id;
                    
                    // 填充表单
                    $('#edit-user-id').val(user.id);
                    $('#edit-username').val(user.username);
                    $('#edit-real-name').val(user.realName || '');
                    $('#edit-email').val(user.email || '');
                    $('#edit-phone').val(user.phone || '');
                    $('#edit-status').val(user.status);
                    $('#edit-password').val(''); // 清空密码字段
                    
                    $('#edit-user-modal').modal('show');
                })
                .catch(function(error) {
                    console.error('获取用户信息失败:', error);
                    showMessage('获取用户信息失败，请稍后重试', 'danger');
                })
                .finally(function() {
                    showLoading(false);
                });
        }

        // 更新用户
        function updateUser() {
            const formData = {
                username: $('#edit-username').val(),
                realName: $('#edit-real-name').val(),
                email: $('#edit-email').val(),
                phone: $('#edit-phone').val(),
                status: parseInt($('#edit-status').val())
            };

            // 如果密码不为空，则添加到formData中
            const password = $('#edit-password').val();
            if (password) {
                formData.password = password;
            }

            // 表单验证
            if (!formData.username || !formData.realName || !formData.email) {
                showMessage('请填写所有必填字段', 'danger');
                return;
            }

            axios.put(`/api/user-management/users/${currentUserId}`, formData)
                .then(function(response) {
                    if (response.data.success) {
                        $('#edit-user-modal').modal('hide');
                        showMessage(response.data.message, 'success');
                        loadUsers(); // 重新加载用户列表
                    } else {
                        showMessage(response.data.message, 'danger');
                    }
                })
                .catch(function(error) {
                    console.error('更新用户失败:', error);
                    showMessage('更新用户失败，请稍后重试', 'danger');
                });
        }

        // 准备删除用户
        function prepareDeleteUser(id, username) {
            currentUserId = id;
            currentUsername = username;
            $('#delete-username').text(username);
            $('#delete-confirm-modal').modal('show');
        }

        // 删除用户
        function deleteUser() {
            axios.delete(`/api/user-management/users/${currentUserId}`)
                .then(function(response) {
                    if (response.data.success) {
                        $('#delete-confirm-modal').modal('hide');
                        showMessage(response.data.message, 'success');
                        loadUsers(); // 重新加载用户列表
                    } else {
                        showMessage(response.data.message, 'danger');
                    }
                })
                .catch(function(error) {
                    console.error('删除用户失败:', error);
                    showMessage('删除用户失败，请稍后重试', 'danger');
                });
        }

        // 切换用户状态
        function toggleUserStatus(id, newStatus, username) {
            const statusText = newStatus === 1 ? '启用' : '禁用';
            
            if (confirm(`确定要${statusText}用户 ${username} 吗？`)) {
                axios.put(`/api/user-management/users/${id}/status`, { status: newStatus })
                    .then(function(response) {
                        if (response.data.success) {
                            showMessage(response.data.message, 'success');
                            loadUsers(); // 重新加载用户列表
                        } else {
                            showMessage(response.data.message, 'danger');
                        }
                    })
                    .catch(function(error) {
                        console.error('切换用户状态失败:', error);
                        showMessage('切换用户状态失败，请稍后重试', 'danger');
                    });
            }
        }

        // 搜索用户
        function searchUsers() {
            const searchTerm = $('#search-input').val().toLowerCase().trim();
            
            if (!searchTerm) {
                renderUserTable(users); // 如果搜索框为空，显示所有用户
                return;
            }
            
            // 根据搜索条件过滤用户
            const filteredUsers = users.filter(function(user) {
                return (
                    (user.username && user.username.toLowerCase().includes(searchTerm)) ||
                    (user.realName && user.realName.toLowerCase().includes(searchTerm)) ||
                    (user.email && user.email.toLowerCase().includes(searchTerm))
                );
            });
            
            renderUserTable(filteredUsers);
        }

        // 显示加载指示器
        function showLoading(show) {
            if (show) {
                $('#loading-indicator').show();
                $('#no-data-message').hide();
                $('#user-table-body').empty();
            } else {
                $('#loading-indicator').hide();
            }
        }

        // 显示消息
        function showMessage(message, type = 'success') {
            const messageElement = $('#message');
            messageElement.removeClass('alert-success alert-danger alert-warning alert-info');
            messageElement.addClass(`alert alert-${type}`);
            $('#message-text').text(message);
            messageElement.show();
            
            // 3秒后自动隐藏消息
            setTimeout(function() {
                messageElement.fadeOut('slow');
            }, 3000);
        }

        // 清除消息
        function clearMessages() {
            $('#message').hide();
        }

        // 格式化日期时间
        function formatDateTime(dateTimeString) {
            if (!dateTimeString) return '-';
            
            try {
                const date = new Date(dateTimeString);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                
                return `${year}-${month}-${day} ${hours}:${minutes}`;
            } catch (error) {
                console.error('格式化日期时间失败:', error);
                return dateTimeString;
            }
        }
    </script>
</body>
</html>